package com.sky.filters;


import com.sky.constant.JwtClaimsConstant;
import com.sky.properties.AdminProperties;
import com.sky.properties.JwtProperties;
import com.sky.properties.UserProperties;
import com.sky.utils.CollUtils;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties({AdminProperties.class, UserProperties.class, JwtProperties.class})
public class UserAdminGlobalFilter implements GlobalFilter, Ordered {

    private final JwtProperties jwtProperties;
    private final AdminProperties adminProperties;
    private final UserProperties userProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        System.out.println(request.getPath());
        // 2.判断是否不需要拦截
        if (isExclude(request.getPath().toString())) {
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }

        // 3.获取请求头中的token
        List<String> headers = request.getHeaders().get("token");
        List<String> auth = request.getHeaders().get("authentication");
        String token = null;
        if (!CollUtils.isEmpty(headers)) {
            token = headers.get(0);
        }
        if (!CollUtils.isEmpty(auth)) {
            token = auth.get(0);
        }
        // 4.校验并解析token
        Long userId = null;

        try {
            // 判断token类型

            // Admin token
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            userId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            return handleUserRequest(exchange, userId, chain);
        } catch (Exception e) {
        }
        try {
            // User token
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            return handleUserRequest(exchange, userId, chain);
        } catch (Exception e) {
        }


        return unauthorizedResponse(exchange);


    }

    private Mono<Void> handleAdminRequest(ServerWebExchange exchange, Long adminId, GatewayFilterChain chain) {
        if (adminId == null) {
            return unauthorizedResponse(exchange);
        }
        // 5.如果有效，传递用户信息
        String userInfo = adminId.toString();
        ServerWebExchange serverWebExchange = exchange.mutate()
                .request(builder -> builder.header("admin-info", userInfo))
                .build();
        // 6.放行
        return chain.filter(serverWebExchange);
    }

    private Mono<Void> handleUserRequest(ServerWebExchange exchange, Long userId, GatewayFilterChain chain) {
        if (userId == null) {
            return unauthorizedResponse(exchange);
        }
        // 处理用户特定的逻辑
        String userInfo = userId.toString();
        ServerWebExchange serverWebExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        // 6.放行
        return chain.filter(serverWebExchange);
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setRawStatusCode(401);
        return response.setComplete();
    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : adminProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, antPath)) {
                return true;
            }
        }
        for (String pathPattern : userProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, antPath)) {
                return true;
            }
        }
        System.out.println(false);
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}